package cn.bdqn.config;

import cn.bdqn.dto.LoginUser;
import cn.bdqn.exception.MyException;
import cn.bdqn.utils.JwtUtil;
import cn.bdqn.utils.RedisCache;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static cn.bdqn.utils.RedisConstants.LOGIN_USER_TOKEN;
import static cn.bdqn.utils.RedisConstants.LOGIN_USER_TTL;
@Slf4j
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取请求统头的token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            // 如果没有token  直接放行放行  后面其他过滤器会拦截
            filterChain.doFilter(request, response);
            return;
        }
        String userid;
        try {
             //解析token
            Claims claims = JwtUtil.parseJWT(token);
            userid = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }
        //从redis中获取用户信息
        log.info("-----------获取到的token为:::"+token);
        String redisKey = LOGIN_USER_TOKEN + userid;
        LoginUser loginUser = redisCache.getCacheObject(redisKey);
        if(Objects.isNull(loginUser)){ //如果等于空  用户未登录

            throw new RuntimeException(String.valueOf(600));
        }
        //存入SecurityContextHolder
        //TODO  获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken =
                //第一个 用户已认证信息 第三个
                new UsernamePasswordAuthenticationToken(loginUser,null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行 刷新用户缓存时间
        redisCache.setCacheObject(redisKey,loginUser,LOGIN_USER_TTL, TimeUnit.MINUTES);
        filterChain.doFilter(request, response);
    }
}
